﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections;
using System.Linq.Expressions;
using System.Diagnostics;

namespace Moose.Common
{
    public class Methods
    {
        //public static void TestPorts()
        //{
        //    List<string> _PortNames = new List<string>();
        //    _PortNames.AddRange(System.IO.Ports.SerialPort.GetPortNames());

        //    SerialPortHelper _SerialPortHelper;
        //    Moose.Model.SerialPortInfo _SerialPortInfo;
        //    string _InstrumentName = string.Empty;
        //    byte[] _SendData;

        //    foreach (Moose.Model.CommonEnum.InstrumentEnum item in Enum.GetValues(typeof(Moose.Model.CommonEnum.InstrumentEnum)))
        //    {
        //        _InstrumentName = GetEnumDescription(item as Enum);
        //        if (item == Moose.Model.CommonEnum.InstrumentEnum.GasSampleCompounderInfo|| item == Moose.Model.CommonEnum.InstrumentEnum.SolenoidValveInfo)
        //        {
        //            continue;
        //        }
        //        Console.WriteLine($"开始查询{_InstrumentName}仪器串口！！！");
        //        for (int i = 0; i < _PortNames.Count; i++)
        //        {
        //            Console.WriteLine($"开始测试{_PortNames[i]}！！！");
        //            _SerialPortInfo = new Model.SerialPortInfo();
        //            _SerialPortInfo.PortName = _PortNames[i];

        //            switch (item)
        //            {
        //                case Model.CommonEnum.InstrumentEnum.SolenoidValveInfo:
        //                case Model.CommonEnum.InstrumentEnum.ConverterPlate:
        //                case Model.CommonEnum.InstrumentEnum.GasSampleCompounderInfo:
        //                    _SerialPortInfo.BaudRate = 9600;
        //                    _SerialPortInfo.DataBits = 8;
        //                    _SerialPortInfo.Parity = System.IO.Ports.Parity.None;
        //                    _SerialPortInfo.StopBits = System.IO.Ports.StopBits.One;
        //                    break;
        //            }
        //            _SerialPortHelper = new SerialPortHelper();
        //            _SerialPortHelper.IniInfo(_SerialPortInfo);
        //            _SerialPortHelper.S_Port_DataReceived += _SerialPortHelper_S_Port_DataReceived;

        //            if (_SerialPortHelper.IsOpen)
        //            {
        //                Console.WriteLine("当前串口已打开！！！");
        //                continue;
        //            }
        //            else
        //            {
        //                _SerialPortHelper.Start();
        //                switch (item)
        //                {
        //                    case Model.CommonEnum.InstrumentEnum.SolenoidValveInfo:
        //                        _SendData = new byte[] { 0x03, 0x01, 0x00, 0x00, 0x00, 0x10, 0x3C, 0x24 };
        //                        break;
        //                    case Model.CommonEnum.InstrumentEnum.ConverterPlate:
        //                        //                        01 04 10 00 00 0A 74 CD
        //                        _SendData = new byte[] { 0x01, 0x04, 0x10, 0x00, 0x00, 0x0A, 0x74, 0xCD };
        //                        break;
        //                    case Model.CommonEnum.InstrumentEnum.GasSampleCompounderInfo:
        //                        //_SendData = new byte[] { (byte)Convert.ToInt32(_PortNames[i].Replace("COM", ""), 16), 0x04, 0x10, 0x00, 0x00, 0x0A, 0x74, 0xCD };
        //                        _SendData = new byte[] { 0, 0, 0 };
        //                        break;
        //                    default:
        //                        _SendData = new byte[] { 0, 0, 0 };
        //                        break;
        //                }

        //                _SerialPortHelper.AddSendOrder(_SendData);
        //                Thread.Sleep(5000);
        //                _SerialPortHelper.Stop();
        //                if (_SerialPortHelper.IsReturn)
        //                {
        //                    Console.WriteLine(_InstrumentName + "串口为：" + _PortNames[i]);
        //                    break;
        //                }
        //                else if (i == _PortNames.Count - 1)
        //                {
        //                    Console.WriteLine(_InstrumentName + "串口未发现");
        //                }
        //            }
        //        }
        //    }
        //    Console.WriteLine("查询完毕！！！");
        //}

        private static void _SerialPortHelper_S_Port_DataReceived(string obj)
        {
            Console.WriteLine(obj);
        }

        /// <summary>
        ///通过枚举类型拿到描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Enum enumValue)
        {
            string str = enumValue.ToString();
            System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
            object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            if (objs == null || objs.Length == 0) return str;
            System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
            return da.Description;
        }

        /// <summary>
        ///通过枚举描述取枚举类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Description"></param>
        /// <returns>若为-1，表示不存在；否则请转换为枚举类型</returns>
        public static int GetEnum<T>(string Description)
        {
            foreach (T item in Enum.GetValues(typeof(T)))
            {
                if (GetEnumDescription(item as System.Enum) == Description)
                {
                    return Convert.ToInt32(item);
                }
            }
            return -1;
        }

        /// <summary>
        /// 结束当前所有进程
        /// 在程序退出时，可以更干净的清除进程
        /// </summary>
        public static void KillCurrPorcess()
        {
            try
            {
                System.Diagnostics.Process CurrPorcess = System.Diagnostics.Process.GetCurrentProcess();
                CurrPorcess.Kill();
            }
            catch { }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// 拼接字符 （''）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string CombiningStrings1<T>(List<T> list)
        {
            string _Result = string.Empty;

            for (int i = 0; i < list.Count; i++)
            {
                _Result += $"'{list[i].ToString()}' , ";
            }
            _Result = _Result.Substring(0, _Result.Length - 2);

            return _Result;
        }

        /// <summary>
        /// 拼接字符 （）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string CombiningStrings2<T>(List<T> list)
        {
            string _Result = string.Empty;

            for (int i = 0; i < list.Count; i++)
            {
                _Result += $"{list[i].ToString()}, ";
            }
            _Result = _Result.Substring(0, _Result.Length - 2);

            return _Result;
        }

        /// <summary>
        /// 获取异常信息
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="backStr"></param>
        /// <returns></returns>
        public static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);

                sb.AppendLine("【异常方法】：" + ex.TargetSite);

            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

        public static Expression<Func<T, bool>> GetConditionExpression<T>(string[] options, string fieldName)
        {
            ParameterExpression left = Expression.Parameter(typeof(T), "c");//c=>
            Expression expression = Expression.Constant(false);
            foreach (var optionName in options)
            {
                Expression right = Expression.Call
                       (
                          Expression.Property(left, typeof(T).GetProperty(fieldName)),  //c.DataSourceName
                          typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),// 反射使用.Contains()方法                         

                          Expression.Constant(optionName)           // .Contains(optionName)
                       );
                expression = Expression.Or(right, expression);//c.DataSourceName.contain("") || c.DataSourceName.contain("") 
            }
            Expression<Func<T, bool>> finalExpression
                = Expression.Lambda<Func<T, bool>>(expression, new ParameterExpression[] { left });
            return finalExpression;
        }

        /// <summary>
        /// 判断进度是否已经运行
        /// </summary>
        /// <returns></returns>
        public static bool CheckProcess()
        {
            Process CurProcess;
            string CurrFileName;
            Process[] ProcessList;
            bool IsExists = false;
            int ProcCount = 0;
            CurProcess = Process.GetCurrentProcess();
            CurrFileName = CurProcess.MainModule.FileName;
            ProcessList = Process.GetProcessesByName(CurProcess.ProcessName);
            foreach (Process process in ProcessList)
            {
                if (process.MainModule.FileName == CurrFileName)
                {
                    ProcCount++;
                    if (ProcCount >= 2)
                    {
                        IsExists = true;
                        break;
                    }
                }
            }
            return IsExists;
        }

        /// <summary>
        /// 判断进度是否已经运行
        /// </summary>
        /// <returns></returns>
        public static bool CheckProcess(string FileName, string ProccessName)
        {
            bool IsExists = false;
            Process[] ProcessList;
            ProcessList = Process.GetProcessesByName(ProccessName);
            if (ProcessList.Length <= 0)
                ProcessList = Process.GetProcessesByName(ProccessName.Replace(".exe", ""));
            foreach (Process process in ProcessList)
            {
                if (process.MainModule.FileName == FileName)
                {
                    IsExists = true;
                    break;
                }
            }
            return IsExists;
        }

        public void CheckProcessDemo()
        {
            Process _CurrentProcess = Process.GetCurrentProcess();
            Process[] _AssociatedProcess = Process.GetProcessesByName(_CurrentProcess.ProcessName);

            int i = 0;
            foreach (var item in _AssociatedProcess)
            {
                if (_CurrentProcess.MainModule.FileName == item.MainModule.FileName)
                {
                    i++;
                    if (i >= 2)
                    {
                        // 当前程序已经运行；
                    }
                }
            }

        }

    }
}
